package com.cdp.web.controller.system;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cdp.common.core.domain.AjaxResult;
import com.cdp.common.core.domain.entity.ChartRecord;
import com.cdp.common.utils.SecurityUtils;
import com.cdp.common.utils.uuid.IdUtils;
import com.cdp.system.dto.ChartDTO;
import com.cdp.system.service.IChartRecordService;
import com.cdp.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping
public class ChartRecordController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IChartRecordService chartRecordService;

    @Value("${file.upload-dir}")
    private String uploadDir;




/*    @ApiOperation("我的生成：新增（新版）")
    @PostMapping("/user/addChart")
    @Transactional
    public AjaxResult addChart(MultipartFile file, String chartName, Long fileId) {
        // 检查文件是否为空
        if (ObjectUtils.isEmpty(file)) {
            return AjaxResult.error(400, "上传文件为空，请重试！");
        }

        Long userId = SecurityUtils.getUserId();

        // 检查图表名称是否重复
        LambdaQueryWrapper<ChartRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChartRecord::getUserChartName, chartName)
                .eq(ChartRecord::getUserId, userId)
                .eq(ChartRecord::getDeleteTime, "0");
        List<ChartRecord> chartRecords = chartRecordService.list(queryWrapper);

        if (!chartRecords.isEmpty()) {
            return AjaxResult.error(409, "图表名称已存在，请更换名称");
        }

        // 生成新文件名
        String originalFilename = file.getOriginalFilename();
        String fileName = createNewFileName(originalFilename);

        try {
            // 保存文件
            File destFile = new File(uploadDir, fileName);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            file.transferTo(destFile);

            // 返回成功结果
            return AjaxResult.success("文件上传成功", destFile.getAbsolutePath());

        } catch (Exception e) {
            // 异常处理
            return AjaxResult.error(500, "文件保存失败：" + e.getMessage());
        }
    }


    private String createNewFileName(String originalFilename) {
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        return System.currentTimeMillis() + "_" + IdUtils.generateRandomNumber() + fileExtension;
    }*/


    //    @ApiOperation("我的生成：新增（新版）")
//    @PostMapping("/user/addFile")
//    @Transactional
//    public AjaxResult addFile(@RequestBody ChartDTO chartDTO) {
//        Long userId = SecurityUtils.getUserId();
//        LambdaQueryWrapper<ChartRecord> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(ChartRecord::getUserChartName, chartDTO.getFileName())
//                .eq(ChartRecord::getUserId, userId)
//                .eq(ChartRecord::getDeleteTime, "0");
//        List<ChartRecord> chartRecords = chartRecordService.list(queryWrapper);
//        if (!chartRecords.isEmpty()) {
//            return AjaxResult.error(409, "图表名称已存在，请更换名称");
//        }
//
//        String number = IdUtils.generateRandomNumber();
//        ChartRecord chartRecord = new ChartRecord();
//        chartRecord.setUserId(userId);
//        chartRecord.setUserChartName(chartDTO.getFileName());
//        chartRecord.setUserChartOption(chartDTO.getIds());
//        chartRecord.setRecordId(Long.valueOf(number));
//        if (chartDTO.getFileId() != null ) {
//            chartRecord.setFileId(chartDTO.getFileId());
//        }
//        chartRecord.setCreateTime(Date.from(Instant.now()));
//        chartRecord.setDeleteTime(0);
//        chartRecord.setSource(chartDTO.getSource());
//        boolean isSaved = chartRecordService.save(chartRecord);
//        if (isSaved) {
//            return AjaxResult.success("图表添加成功");
//        } else {
//            return AjaxResult.error("图表添加失败，请稍后重试");
//        }
//    }
    @ApiOperation("我的生成：新增（新版）")
    @PostMapping("/user/addFile")
    @Transactional
    public AjaxResult addFile(@RequestBody ChartDTO chartDTO) {
        Long userId = SecurityUtils.getUserId();
        if(chartDTO.getSource()==null){
            return AjaxResult.error(400,"source为空，请重试!");
        }

        if(chartDTO.getFileName().isEmpty()){
            return AjaxResult.error(400,"fileName为空，请重试!");
        }

        if(chartDTO.getIds().isEmpty()){
            return AjaxResult.error(400,"ids为空，请重试!");
        }


        // 检查文件名是否已存在
        LambdaQueryWrapper<ChartRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChartRecord::getUserChartName, chartDTO.getFileName())
                .eq(ChartRecord::getUserId, userId)
                .eq(ChartRecord::getDeleteTime, 0);  // 仅查询未删除的记录
        List<ChartRecord> chartRecords = chartRecordService.list(queryWrapper);
        if (!chartRecords.isEmpty()) {
            return AjaxResult.error(409, "图表名称已存在，请更换名称");
        }

        // 生成一个唯一的记录ID
        Integer number = IdUtils.generateRandomNumber();
        ChartRecord chartRecord = new ChartRecord();
        chartRecord.setUserId(userId);
        chartRecord.setUserChartName(chartDTO.getFileName());   // 设置文件名
        chartRecord.setUserChartOption(JSON.toJSONString(chartDTO.getIds()));  // 设置图表选项，假设 ids 是一个列表
        chartRecord.setRecordId(Long.valueOf(number));  // 设置记录ID

        // 如果 fileId 存在，设置 fileId
        if (chartDTO.getFileId() != null) {
            chartRecord.setFileId(Long.valueOf(chartDTO.getFileId()));  // 假设 fileId 是 String 类型，需要转换为 Long
        }

        // 设置图表来源
        chartRecord.setSource(chartDTO.getSource());
        // 设置创建时间和删除时间
        chartRecord.setCreateTime(Date.from(Instant.now()));
        chartRecord.setDeleteTime(0);  // 0 表示未删除
        chartRecord.setStatus(0);
        chartRecord.setVersion(0);
        // 保存图表记录
        boolean isSaved = chartRecordService.save(chartRecord);
        if (isSaved) {
            return AjaxResult.success("图表添加成功");
        } else {
            return AjaxResult.error("图表添加失败，请稍后重试");
        }
    }


}

